# -*- coding: utf-8 -*-
import logging
import threading
from zc_core.client.mongo_client import Mongo

logger = logging.getLogger('SkuHelper')


class SpuHelper(object):
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(SpuHelper, "_instance"):
            with SpuHelper._instance_lock:
                if not hasattr(SpuHelper, "_instance"):
                    SpuHelper._instance = object.__new__(cls)
        return SpuHelper._instance

    def __init__(self):
        if not self._biz_inited:
            self._biz_inited = True
            self.spu_mapper = dict()
            rows = Mongo().list('item_data_pool', query={'spuId': {'$exists': True}}, fields={'_id': 1, 'spuId': 1})
            for row in rows:
                self.spu_mapper[row.get('_id')] = row.get('spuId')
            logger.info('SPU映射: %s' % len(self.spu_mapper))

    def get_spu_id(self, sku_id):
        if sku_id:
            return self.spu_mapper.get(sku_id)

        return None
